/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.controllers', [])
    .controller('MainCtrl',function($scope,$state,$window,MainService,AuthenticationService){
        if(localStorage.getItem('token')){
            AuthenticationService.isLogged = true;
        }
        $scope.islogin = AuthenticationService.isLogged;
        $('#slides2').slidesjs({
            width: 940,
            height: 528,
            navigation: false,
            start: 3,
            play: {
                auto: true
            }
        });

        $scope.myScroll = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        $scope.popQuery = false;
        $scope.go = function(type){
            switch (type){
                case 1:
                    $state.go('tab.transfer');
                    break;
                case 2:
                    $state.go('tab.myTransfer',{random:false});
                    break;
                case 3:
                    $state.go('tab.myOrders');
                    break;
                case 4:
                    $state.go('tab.center');
                    break;
                case 5://注销
                    //$state.go('tab.center');
                    /*$state.go('query');*/
                    $scope.popQuery = true;
                    $('#pop1button1').click(function(e)
                    {
                        $scope.popQuery=false;
                        setTimeout(function(){
                            $scope.$apply();
                        },500);

                    });

                    break;
                    /*AuthenticationService.isLogged = false;
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');*/
                    /*delete $window.sessionStorage.token;
                    delete $window.sessionStorage.user;*/
                   /* window.localStorage.setItem('token',data.token);
                    window.localStorage.setItem('user',JSON.stringify(data.user));*/

                    break;
                case 6:
                    $state.go('register');
                    break;
                case 7:
                    $state.go('login');
                    break;
                case 8:
                    $state.go('tab.mySuggest');
                    break;
            }


        }
    })
    .controller('TransferCtrl',function($scope,$state,$timeout,$interval,LoginService,$location,TransferService){
        //alert(TransferService.getInforData().startCityId+' '+TransferService.getInforData().startCity);
        //$scope.citys =[{name:'广州'},{name:'哈尔滨'},{name:'西安'},{name:'南京'},{name:'哈尔滨'},{name:'西安'},{name:'南京'}];

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.inforData = {};
        if(!TransferService.getCityList().length>0){//如果初始化过城市则不再请求，直接赋值到页面
            TransferService.getCitys($scope);
        }/*else{*/
            $scope.inforData = TransferService.getInforData();
        //}
        console.log(TransferService.getInforData());
        $scope.pop1=false;
        $scope.showinput=false;
        $scope.isDisabled=true;
        var msgcode;
        $scope.user = {btnVal:' 获取验证码 '};


        if(localStorage.getItem('user')){
            $scope.inforData.phone = Number(JSON.parse(localStorage.getItem('user')).phone)
        }

        var firstphone=$scope.inforData.phone;
        $scope.updatephone=firstphone;
        $scope.getCode1=function(phone){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if(phone==null||phone.length<11){
                $scope.pop1 = true;
                $scope.content = '请输入正确手机号码';
                return false;
            }
            LoginService.getCode(phone,'phoneCode')
                .success(function(data,status){
                    if(data=='err'){
                        $scope.pop1 = true;
                        $scope.content = '验证码获取失败！';
                        return false;
                    }
                    msgcode=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            msgcode=undefined;
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.pop1 = true;
                    $scope.content = '验证码获取失败！';
                    return false;
                });
        }
        $scope.goNext = function(){
            //console.log($scope.inforData.startTime+"----"+new Date().toLocaleDateString());
            function daysBetween(DateOne,DateTwo)
            {
                var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));
                var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);
                var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));

                //var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('/'));
                //var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('/')+1);
                //var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('/'));
                var date = new Date();
                var month = date.getMonth()+1;
                var day = date.getDate();
                if(month<10){
                    month = '/0'+month;
                }else{
                    month = '/'+month
                }
                if(day<10){
                    day = '/0'+day;
                }else{
                    day = '/'+day;
                }
                var dd = date.getFullYear()+month+day;
                var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(dd))/86400000);
                return cha;
            }
            var isstartDate=daysBetween($scope.inforData.startTime);
            var isendDate=daysBetween($scope.inforData.endTime);

            if($scope.inforData.username==''||$scope.inforData.phone==''||new Date($scope.inforData.startTime).getTime()>new Date($scope.inforData.endTime).getTime()||isstartDate<0||isendDate<0) {
                if (new Date($scope.inforData.startTime).getTime() > new Date($scope.inforData.endTime).getTime()) {
                    $scope.pop1 = true;
                    $scope.content = "到达日期不能早于出发日期。";
                    return false;
                } else if($scope.inforData.username==''||$scope.inforData.phone==''){
                    $scope.pop1 = true;
                    $scope.content = "请填写用户姓名和手机号码！";
                    return false;
                }else if(isstartDate<0||isendDate<0){
                    $scope.pop1 = true;
                    $scope.content = "启程或到货日期不能小于当前日期！";
                    return false;
                }

            }else{
                if($scope.inforData.phone==firstphone){
                    $state.go('tab.transferAddCar');
                }else{
                    if($scope.code){
                        if($scope.code==msgcode){
                            $state.go('tab.transferAddCar');
                        }else{
                            $scope.pop1 = true;
                            $scope.content="验证码错误，请重新输入！";
                            return false;
                        }
                    }else{
                        $scope.pop1 = true;
                        $scope.content="请验证修改后的手机号码！";
                        return false;
                    }

                }
            }
        }

     /* $scope.pop1button = document.getElementById('pop1button');
        $scope.pop1button.addEventListener('tap', function (e) {

            $scope.pop1=false;
            setTimeout(function(){
                    $scope.$apply();
                },500)
        }, false);*/
        $('#pop1button').click(function(e)
        {
            $scope.pop1=false;
            setTimeout(function(){
                $scope.$apply();
            },500);

        });
        //$scope.inforData.phone = Number(JSON.parse(localStorage.getItem('user')).phone);
        $scope.selectCity = function(type){//1起点 2目的地
            //alert(type);
            TransferService.getInforData().username = $scope.inforData.username;
            TransferService.getInforData().phone = $scope.inforData.phone;
            /*TransferService.getInforData().startTime = $("#date1").val();
            TransferService.getInforData().endTime = $("#date2").val();*/
            $state.go('tab.citys',{type:type});
        }
        $("#dtBox").DateTimePicker({//各平台兼容性不同，创建了两个实例
            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date1"));
                });

            }
        });
        $("#dtBox1").DateTimePicker({

            addEventHandlers: function()
            {
                var dtPickerObj = this;

                $("#pickerButton1").click(function(e)
                {
                    e.stopPropagation();
                    dtPickerObj.showDateTimePicker($("#date2"));
                    dtPickerObj._setCurrentDate();
                });
            }
        });

        $('#date1').bind('change',function(){//jquery监听隐藏文本框值变化

            TransferService.getInforData().startTime = this.value;
            $scope.inforData.startTime = this.value;

            $scope.$apply();
            $scope.myScroll.refresh();

        });
        $('#date2').bind('change',function(){
            //if(new Date($scope.inforData.startTime)>new Date(this.value)){
            //    alert('到达日期不能早于出发日期');
            //    return;
            //}
            TransferService.getInforData().endTime = this.value;
            $scope.inforData.endTime = this.value;

            $scope.$apply();
            $scope.myScroll.refresh();
        });

        $scope.$watch('inforData.phone',function(newValue,oldValue, scope){
            if(newValue!=oldValue){
                setTimeout(function(){
                    $scope.$apply();
                    $scope.myScroll.refresh();
                },500);

            }

        });

    })
    .controller('MyTransferCtrl',function($scope,$state,MyTransferService){
        //$scope.datas=MyTransferService.getMytransferData().datas;

        $scope.go = function(go,trans,nums){
            if(go==1){
                $state.go('tab.outDetails',{startstation:trans.startstation,endstation:trans.endstation,starttime:trans.starttime,endtime:trans.endtime,type:trans.type,num:trans.num,carnum:trans.carnum,nums:nums,infoid:trans.id});
            }else if(go==2){
                $state.go('tab.myTransfer2',{inforid:trans.id,name:trans.username,phone:trans.phone});
            }

        }
    })
    .controller('myTransfer2',function($scope,$rootScope,$http,$state,LoginService,$stateParams,TransferService){
      /*  $scope.myScroll = new IScroll('#wrapperTran', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
*/
        $scope.hid=false;
        $scope.pop1=false;
        //$scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        //document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.goBack = function() {
            $state.go('tab.myTransfer');
        }
        $scope.goCompany=function(inforid,userid){
            $state.go('tab.companyDet',{inforid:inforid,userid:userid});
        }
        $scope.accept=function(inforid,data){
            $scope.pop1=true;
            $scope.content="确定接受报价吗？";
            $scope.inforid=inforid;
            $scope.data=data;
            $scope.typebtn=1;
            console.log(data);
        }
        $scope.cancelPop=function(){
            $scope.pop1=false;
        }
        $scope.confirm=function(typebtn,inforid,data,name,myphone){
            var user = $scope.user = JSON.parse(localStorage.user);
            console.log(data);
            if(typebtn==1){
                $scope.pop1=false;
                var promise = $http({
                    method:'POST',
                    url:'/accept',
                    data:{
                        inforid:inforid,
                        data:data
                    }
                });
                promise.success(function(datas) {
                    console.log(datas);
                    if(datas){
                        if(user.nickname){
                            LoginService.accept(data.phone,user.nickname,myphone)
                                .success(function(data,status){
                                }
                            );
                        }else{
                            LoginService.accept(data.phone,false,myphone)
                                .success(function(data,status){
                                }
                            );
                        }

                        $rootScope.refreshOrder = true;
                        $state.go('tab.completeQuo',{isOk:data});
                    }else{
                        $scope.pop1=true;
                        $scope.content="接受报价失败，请重试。";
                        $scope.typebtn=2;
                    }
                });
            }else{
                $scope.pop1=false;
            }

        }

    })
    .controller('Query',function($scope,$state,$stateParams,$rootScope,$http,$location,TransferService){
        if(!$rootScope.isWechat){
            $rootScope.isWechat = $stateParams.isWechat;
        }
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        $scope.subQuery = function(inforData){  //点击添加
            var promise = $http({
                method:'POST',
                url:'/queryPrice',
                data:{
                    inforData:inforData
                }
            });
            promise.success(function(data) {
                $scope.num=data.num;
                $scope.price=data.price;
            });
        }

        $scope.inforData = {};
        if(!TransferService.getCityList().length>0){//如果初始化过城市则不再请求，直接赋值到页面
            TransferService.getCitys($scope);
        }else{
            $scope.inforData = TransferService.getInforData();
        }

        $scope.selectCity = function(type){//1起点 2目的地
            $state.go('AddCitys',{type:type});
        }
    })
    .controller('AddCitys',function($scope,$state,$stateParams,TransferService){
        $scope.citys = TransferService.getCityList();
        $scope.allcitys = TransferService.getAllCitys();
        $scope.provinces = TransferService.getProvince();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        $scope.myScroll1 = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
            $scope.myScroll1.refresh();
        },500);
        $scope.goBack = function(){
            $state.go('query');
        };
        $scope.selectCity = function(id,province,city){//判断上一页面传来的值是1则改变事发地点2为目的地
            if($stateParams.type==1){
                TransferService.getInforData().startCityId = id;
                TransferService.getInforData().startCity = province+" "+city;

            }else if($stateParams.type==2){
                TransferService.getInforData().endCityId = id;
                TransferService.getInforData().endCity = province+" "+city;
            }
            $state.go('query');
        };

        $scope.selectProvince = function(province){/*选择省份*/
            var citys = [];
            for(var i=0;i<$scope.allcitys.length;i++){
                if(province==$scope.allcitys[i].province){
                    citys.push($scope.allcitys[i]);
                }
            }
            $scope.citys = citys;
            //this.style.backgroundColor=this.style.backgroundColor==''?'#a00':'';return false;
            /*$(this).css('color','#a00');*/
            setTimeout(function(){
                $scope.$apply();
                $scope.myScroll1.refresh();

            },500);
        }
    })

    .controller('OutDetails',function($scope,$state,$http,$stateParams,TransferService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        var startstation=$stateParams.startstation;
        var endstation=$stateParams.endstation;
        var starttime=$stateParams.starttime;
        var endtime=$stateParams.endtime;
        var type=$stateParams.type;
        var num=$stateParams.num.split(',');
        var carnums=$stateParams.carnum;
        var nums=$stateParams.nums;
        var infoid=$stateParams.infoid;
        var brand=carnums.split(',');
        $scope.popup=2;
        var  promise = $http({
            method:'POST',
            url:'/outDetails',
            data:{
                carnum:carnums
            }
        });
        promise.success(function(data,status) {

            $scope.startstation = startstation;
            $scope.endstation=endstation;
            $scope.starttime=starttime;
            $scope.endtime=endtime;
            $scope.carnum=num; //辆数
            $scope.type=type; //类型(板车or拼装)
            $scope.infoid=infoid; //发车单id
            var docs=[]; //品牌id，品牌，型号

            for(var i=0;i<brand.length;i++){
                for(var j=0;j<data.result.length;j++){
                    if(brand[i]==data.result[j].id.toString()){
                        var doc={};
                        doc.bid=data.result[j].id.toString(); //品牌id
                        doc.num=data.result[j].num;  // 型号
                        doc.carbrand=data.result[j].carbrand; //品牌
                        docs.push(doc);
                    }else{
                    }
                }
            }

            $scope.result = docs;

            //删除拼车
            //$scope.delete = function($index){
            //    if(num.length>1){
            //        num.splice($index,1);
            //        docs.splice($index,1);
            //        brand.splice($index,1);
            //        infoNum=num;
            //        infoBrand=brand;
            //    }else{
            //        alert('订单不能为空。')
            //    }
            //}
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                //$scope.$apply(element);
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $scope.pop1=false;
        $scope.pop = function(num,index,doc){
            if(num==1){  //1为取消
                $scope.pop1=true;
                $scope.content="确定取消此发布单吗？";
                $scope.typebtn=1;
            }else if(num==2){ //2为修改
                if(doc==0){
                    $scope.pop1=true;
                    $scope.content="确定修改此发布单吗？";
                    $scope.typebtn=2;
                    $scope.ind=index;
                    $scope.docc=0;
                }else{
                    $scope.pop1=true;
                    $scope.content="确定修改此发布单吗？";
                    $scope.typebtn=2;
                    $scope.ind=index;
                    $scope.docc=doc;
                }
            }
        }
        $scope.cancelPop = function(){
            $scope.pop1=false;
        }
        $scope.confirm = function(typebtn,infoid,type,index,doc){
            if(typebtn==1){
                var  promise = $http({
                    method:'POST',
                    url:'/updateCancel',
                    data:{
                        id:infoid
                    }
                });
                promise.success(function(data) {
                    $state.go('tab.myTransfer',{random:'update'});
                });
            }else if(typebtn==2){
                if(type==1){
                    if(num.length>1){
                        num.splice(index,1);
                        doc.splice(index,1);
                        brand.splice(index,1);
                        infoNum=num;
                        infoBrand=brand;
                        var  promise = $http({
                            method:'POST',
                            url:'/updateOut',
                            data:{
                                carnum:infoBrand,
                                num:num,
                                id:infoid
                            }
                        });
                        promise.success(function(data) {
                            if(data){
                                $scope.pop1=false;
                                //$state.go('tab.myTransfer',{random:'update'});
                            }
                        });
                    }else{
                        $scope.content="发布单车辆不能为空。";
                    }
                }else{
                    if(num.length>1){
                        num.splice(index,1);
                        if(doc==12){
                            brand[0]=brand[0]-1;
                        }else{
                            brand[1]=brand[1]-1;
                        }
                        infoSNum=num;
                        infoSBrand=brand;
                        var  promise = $http({
                            method:'POST',
                            url:'/updateScooter',
                            data:{
                                num:num,
                                id:infoid,
                                carnum:infoSBrand
                            }
                        });
                        promise.success(function(data) {
                            if(data){
                                $scope.pop1=false;
                                //$state.go('tab.myTransfer',{random:'update'});
                            }
                        });
                    }else{
                        $scope.content="发布单车辆不能为空。";
                    }

                }
            }
        }
        $scope.goBack = function(){
            $state.go('tab.myTransfer');
        }
    })
    .controller('companyDet',function($scope,$state,$http,$stateParams,TransferService){
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, true);
        var inforid=$stateParams.inforid;
        var userid=$stateParams.userid;
        var  promise = $http({
            method:'POST',
            url:'/companyDet',
            data:{
                userid:userid
            }
        });
        promise.success(function(data) {
            $scope.introduce=data[0].introduce; //用户自我介绍
            $scope.address=data[0].address;  //地址
            $scope.company=data[0].company;  //公司名称
            $scope.authstate=data[0].authstate; //是否认证
            $scope.attitude=data[0].attitude; //服务态度
            $scope.care=data[0].care; //关心货物
            $scope.corresponds=data[0].corresponds; //符合程度
            $scope.evaluationnum=data[0].evaluationnum; //评分总人数
            $scope.licences=data[0].licences  //营业执照
            $scope.roadlicences=data[0].roadlicences;  //道路运输许可证
            $scope.headerpath=data[0].headerpath;  //头像
            $scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];

            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.$apply(element);
                if(scope.myScroll){
                    scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },500);
        });
        $scope.goBack = function(){
            $state.go('tab.myTransfer2',{inforid:inforid});
        }
        $scope.data=4;
        $scope.graderArray=[{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"},{grader:"1"}];
    })
  /*  .controller('SearchCtrl',function($scope,$q){
        //$scope.tests = [{name:'西安'},{name:'南京'},{name:'上海'},{name:'广州'},{name:'哈尔滨'},{name:'西安'},{name:'南京'}];

        $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];


        $scope.onReload = function() {
            console.warn('reload');
            var deferred = $q.defer();
            setTimeout(function() {
                deferred.resolve(true);
            }, 1000);
            return deferred.promise;
        };
    })*/
    .controller('LoginCtrl',function($scope,$state,$window,$timeout,LoginService,AuthenticationService){

        /*$scope.$watch('user.isRemember',function(value){
            if(value){
                console.log(value);
            }
        });*/
        //alert(localStorage.getItem('token')+'   '+localData.getItem('tokens'));
        $scope.login = function(){
            LoginService.login($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    //alert(data.message+' sssss '+data.user.nickname);
                    /*if(data.message==false){
                        $scope.logInfo = '用户名或密码错误';
                        $timeout(function(){
                            $scope.logInfo = '';
                        },3000);
                        return;
                    }else if(data.message==true){
*/
                    /*if(data==false){
                        $scope.logInfo = '登录失败';
                        return;

                    }*/
                    AuthenticationService.isLogged = true;//认证成功
                    /*$window.sessionStorage.token = data.token;//保存token
                    $window.sessionStorage.user = JSON.stringify(data.user);*/
                    //localData.getItem('tokens',data.token);
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    localStorage.setItem('token',data.token);
                    localStorage.setItem('user',JSON.stringify(data.user));

                    $state.go('/');
                    //}
                }).error(function (data,status) {
                    $scope.logInfo = '登录失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
    })
    .controller('ResetPassCtrl',function($scope,$state,$window,$timeout,$interval,LoginService,AuthenticationService){
        $scope.msgcode1='';
        $scope.user = {btnVal:' 获取验证码 '};

        $scope.logInfo='';
        $scope.getCode = function(){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if($scope.user.phone==null||$scope.user.phone.length<11){
                $scope.logInfo = '请输入正确手机号码';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            if($scope.user.password==null||$scope.user.password.length<6){
                $scope.logInfo = '密码不能小于6位';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            LoginService.getCode($scope.user.phone,'resetPass')
                .success(function(data,status){
                    if(data=='nouser'){
                        return $scope.logInfo = '账号不存在！';

                    }else if(data=='err'){
                        return $scope.logInfo = '验证码获取失败！';
                    }

                    $scope.msgcode1=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            $scope.msgcode1='';
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.logInfo = '获取验证码失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $scope.reset = function(){
            if($scope.user.msgcode!=$scope.msgcode1){
                $scope.logInfo = '验证码错误！';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }
            LoginService.resetPass($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    if(data.msg==true){
                        AuthenticationService.isLogged = false;
                        /*delete $window.sessionStorage.token;
                        delete $window.sessionStorage.user;*/
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        $state.go('login');
                    }

                }).error(function (data,status) {
                    $scope.logInfo = '重置失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }

    })
    .controller('RegisterCtrl',function($scope,$state,$window,$timeout,$interval,LoginService,AuthenticationService){
        $scope.msgcode1='';
        $scope.user = {btnVal:' 获取验证码 '};
        $scope.loginMsg='';
        $scope.lmsg = false;
        $scope.logInfo='';
        $scope.getCode = function(){
            if(!isNaN($scope.user.btnVal)){
                return;
            }
            if($scope.user.phone==null||$scope.user.phone.length<11){
                $scope.logInfo = '请输入正确手机号码';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }

            if($scope.user.password==null||$scope.user.password.length<6){
                $scope.logInfo = '密码不能小于6位';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }
            LoginService.getCode($scope.user.phone,'register')
                .success(function(data,status){
                    if(data=='hasuser'){
                        return $scope.logInfo = '账号已存在！';

                    }else if(data=='err'){
                        return $scope.logInfo = '验证码获取失败！';
                    }


                    $scope.msgcode1=data;
                    $scope.user.btnVal=60;
                    var timer = $interval(function(){
                        $scope.user.btnVal-=1;
                        if($scope.user.btnVal==0){
                            $scope.user.btnVal='  重新获取  ';
                            $scope.msgcode1='';
                            $interval.cancel(timer);
                        }
                    },1000);

                }).error(function (data,status) {
                    $scope.logInfo = '获取验证码失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }
        $scope.register = function(){
            /*if($scope.user.msgcode!=$scope.msgcode1){
                $scope.logInfo = '验证码错误！';
                $timeout(function(){
                    $scope.logInfo = '';
                },3000);
                return;
            }*/
            console.log('sssssss');
            LoginService.register($scope.user.phone,$scope.user.password)
                .success(function(data,status){
                    if(data.msg==true){
                        AuthenticationService.isLogged = false;
                        /*delete $window.sessionStorage.token;
                        delete $window.sessionStorage.user;*/
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        var countdown=5;
                        var dian='.'

                        /*$state.go('/');*/
                        LoginService.login($scope.user.phone,$scope.user.password)
                            .success(function(data,status){
                                AuthenticationService.isLogged = true;//认证成功
                                localStorage.setItem('token',data.token);
                                localStorage.setItem('user',JSON.stringify(data.user));
                                $scope.lmsg = true;
                                $scope.loginMsg = '自动登录'+dian+'  '+countdown;
                                countdown-=1;
                                dian+='.';
                                var time = $interval(function(){
                                    $scope.loginMsg = '自动登录'+dian+'  '+countdown;
                                    if(countdown == 0){
                                        $interval.cancel(time);
                                        $state.go('/');
                                    }
                                    countdown-=1;
                                    dian+='.';

                                },1000);

                            }).error(function (data,status) {
                                $scope.logInfo = '登录失败';
                                $timeout(function(){
                                    $scope.logInfo = '';
                                },3000);
                            });

                    }

                }).error(function (data,status) {
                    $scope.logInfo = '注册失败';
                    $timeout(function(){
                        $scope.logInfo = '';
                    },3000);
                });
        }

    })
    .controller('TabCtrl',function($scope,$state,$window,$location,$rootScope,LoginService){
        //alert('sssss');
       // document.getElementById('footer')
        $rootScope.num1;
        $rootScope.num2;
        $rootScope.num3;
        $rootScope.num4;
        if($location.$$url.indexOf('transfer')>-1){
            $rootScope.num1=1;

        }else if($location.$$url.indexOf('myTransfer')>-1){
            $rootScope.num2=1;

        }else if($location.$$url.indexOf('myOrders')>-1){
            $rootScope.num3=1;

        }else if($location.$$url.indexOf('center')>-1){
            $rootScope.num4=1;
        }

        $rootScope.setColor = function(index){
            setCo();
            changeCo(index);
            console.log('sss');
        }
        function setCo(){
            $rootScope.num1=2;
            $rootScope.num2=2;
            $rootScope.num3=2;
            $rootScope.num4=2;
        }

        function changeCo(index){
            switch (index){
                case 1:
                    $rootScope.num1=1;
                    break;
                case 2:
                    $rootScope.num2=1;
                    break;
                case 3:
                    $rootScope.num3=1;
                    break;
                case 4:
                    $rootScope.num4=1;
                    break;
            }

        }
    })
    .controller('CitysCtrl',function($scope,$state,$stateParams,TransferService){
        $scope.citys = TransferService.getCityList();
        $scope.allcitys = TransferService.getAllCitys();
        $scope.provinces = TransferService.getProvince();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        $scope.myScroll1 = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
            $scope.myScroll1.refresh();
        },500);
        $scope.goBack = function(){
            $state.go('tab.transfer');
        };
        $scope.selectCity = function(id,province,city){//判断上一页面传来的值是1则改变事发地点2为目的地
            //console.log(province+" "+city);
            if($stateParams.type==1){
                TransferService.getInforData().startCityId = id;
                TransferService.getInforData().startCity = province+" "+city;

            }else if($stateParams.type==2){
                TransferService.getInforData().endCityId = id;
                TransferService.getInforData().endCity = province+" "+city;
            }
            $state.go('tab.transfer');
        };

        $scope.selectProvince = function(province){
            var citys = [];
            for(var i=0;i<$scope.allcitys.length;i++){
                if(province==$scope.allcitys[i].province){
                    citys.push($scope.allcitys[i]);
                }
            }
            $scope.citys = citys;
            //this.style.backgroundColor=this.style.backgroundColor==''?'#a00':'';return false;
            /*$(this).css('color','#a00');*/
            setTimeout(function(){
                $scope.$apply();
                $scope.myScroll1.refresh();

            },500);
        }
    })
    .controller('TransferAddCarCtrl',function($scope,$state,$stateParams,$window,TransferService,CropperService){
        if(!TransferService.getCarbrandList().carbrand.length>0){
            TransferService.getCarbrands($scope);//查询汽车品牌
        }

        $scope.visible = true;
        $scope.color = 1;
        $scope.color1 = 2;
        $scope.toggle = function (t) {//显示隐藏零散车辆和整板车辆
            if(t==1){
                $scope.visible = true;
                $scope.color = 1;
                $scope.color1 = 2;
                $scope.inforData.type = 1;
                TransferService.getCurrenttab().state = false;
            }else{
                $scope.visible = false;
                $scope.color1 = 1;
                $scope.color = 2;
                $scope.inforData.type = 2;//设置发车类型
                TransferService.getCurrenttab().state = true;
            }
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                $scope.myScroll.refresh();
            },500);
        }

        $scope.inforData = TransferService.getInforData();
        $scope.currentcar = TransferService.getCurrentCar();//当前显示的品牌和型号
        $scope.currentcar.cropper = CropperService.getCropperdata()[0];
        $scope.currentcar.filepath = CropperService.getCropperdata()[0].filename;
        $scope.currentcar.filename = CropperService.getCropperdata()[0].filepath;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,tap:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        if(TransferService.getCurrenttab().state){//设置那个tab显示
            $scope.visible = false;
            $scope.color1 = 1;
            $scope.color = 2;
            $scope.inforData.type = 2;//设置发车类型
        }

        setTimeout(function(){//延迟绑定点击事件
            $scope.myScroll.refresh();
            $scope.up = document.getElementById('uploadImg');
            $scope.cl = document.getElementById('uploadfile');
            $scope.carbrand = document.getElementById('carbrand');
            $scope.carnum = document.getElementById('carnum');
            $scope.plusnum = document.getElementById('plusnum');
            $scope.minusnum = document.getElementById('minusnum');
            $scope.dray11 = document.getElementById('dray11');
            $scope.dray22 = document.getElementById('dray22');
            /*$scope.goback = document.getElementById('goback');*/
            /*$scope.cl.addEventListener('tap', function () {
                alert('dddddd');
            }, false);*/
            var element = document.getElementById("mytext");
            if("\v"=="v") {
                element.onpropertychange = webChange;
            }else{
                element.addEventListener("input",webChange,true);
            }
            function webChange(){
                var r = /^\+?[1-9][0-9]*$/;
                console.log(element.value);
                if(r.test(element.value)){
                    $scope.currentcar.carnumber=element.value;
                }else{
                    $scope.currentcar.carnumber = 1;
                    element.value="1";
                }
            }
            $scope.up.addEventListener('tap', function () {
                $state.go('tab.cropper',{scale1:4,scale2:3,width:640,height:480,urltype:'transfer'});
                //$('#uploadfile').click();//点击隐藏的文件上传按钮
            }, false);
            $scope.carbrand.addEventListener('tap', function () {

                $state.go('tab.getCarBrandList');
            }, false);
            $scope.carnum.addEventListener('tap', function () {
                /*alert('nnnnnnnn');*/
                $state.go('tab.getCarNumList');
            }, false);
            $scope.plusnum.addEventListener('tap', function () {
                $scope.currentcar.carnumber+=1;
                //$scope.inforData.carnumber+=1;
                $scope.$apply();
                //TransferService.getInforData().carnumber =  $scope.inforData.carnumber;
                console.log($scope.inforData.carnumber);
            }, false);
            $scope.minusnum.addEventListener('tap', function () {
                if($scope.currentcar.carnumber==1){
                    return;
                }
                $scope.currentcar.carnumber-=1;
                //$scope.inforData.carnumber-=1;
                $scope.$apply();
                //TransferService.getInforData().carnumber =  $scope.inforData.carnumber;
            }, false);
            /*$scope.goback.addEventListener('tap', function () {
             $state.go('tab.transfer');//返回到上一页
             }, false);*/
            $scope.dray11.addEventListener('tap', function () {
                $('#dray1').click();
            }, false);
            $scope.dray22.addEventListener('tap', function () {
                $('#dray2').click();
            }, false);
        },500);

        $scope.goBack = function(){
            $state.go('tab.transfer');
        };
        $scope.Carlist = function(){
            $state.go('tab.carlist');
        }
        $scope.goCropper = function(){
            $state.go('tab.cropper');
        }
        $scope.issave=true;

        $scope.savetransfer = function(){
            if($scope.inforData.username==''||$scope.inforData.phone==''){
                alert('请返回填写用户姓名和手机号码')
                return;
            }
            if(!$scope.issave){//判断保存状态，正在保存直接返回
               /* alert('ssss');*/
                return;
            }
            //零散车辆类型并且carnum大于0，不存在添加当前页面数据到数组
            if($scope.inforData.type==2){//整板车类型不需要把当前页面默认选中的值添加进来
                if($scope.inforData.draynum.length<1){
                   /* alert('您还没有添加板车');
                    return;*/
                    $scope.inforData.draynum.push($scope.dray.value);
                    if($scope.dray.value==12){
                        $scope.inforData.draytype[0]+=1;
                        $scope.dray.smallnum+=1;
                    }else{
                        $scope.inforData.draytype[1]+=1;
                        $scope.dray.bignum+=1;
                    }
                    $scope.dray.value = 12;
                }
                $scope.issave=false;
                TransferService.savetransfer()
                    .success(function(data,status){
                        $scope.issave=true;
                    if(data){

                        TransferService.resetInforData();
                        $scope.currentcar = TransferService.resetCurrentCar();
                        $state.go('tab.complete',{isOk:true});
                        //alert('发布成功');
                    }else{
                        $state.go('tab.complete',{isOk:false});
                    }
                }).error(function(data,status){
                        $state.go('tab.complete',{isOk:false});
                        $scope.issave=true;
                });
            }else if($scope.inforData.type==1){//&&$scope.inforData.carnum.length>0
                if($scope.currentcar.brand=='品牌'||$scope.currentcar.num=='型号'||$scope.currentcar.carnumber<=0){//||$scope.currentcar.filepath==''

                    if($scope.inforData.carnum.length<1){
                            return alert('请检查是否选择正确');
                        }
                }else{
                    $scope.inforData.carnum.push($scope.currentcar);
                }
                $scope.currentcar = TransferService.resetCurrentCar();
                $scope.issave=false;
                TransferService.savetransfer()
                    .success(function(data,status){
                        $scope.issave=true;
                        if(data){
                            CropperService.getCropperdata()[0]={
                                scale1:'',
                                scale2:'',
                                width:'',
                                height:'',
                                filename:'',
                                filepath:'上传照片，增加竞价积极性'
                            };
                            TransferService.resetInforData();//重置页面数据
                            $scope.currentcar = TransferService.resetCurrentCar();
                            $state.go('tab.complete',{isOk:true});
                            //alert('发布成功');
                        }else{
                            $state.go('tab.complete',{isOk:false});
                        }


                    }).error(function(data,status){
                        $scope.issave=true;
                        $state.go('tab.complete',{isOk:false});
                    });
            }

        };
        $scope.addNum=$scope.inforData.carnum.length;
        $scope.dray=TransferService.getDray();
        //var currentcar = $scope.currentcar;
        $scope.addCar = function(type){//添加车辆
            if(type==1){
                if($scope.currentcar.brand=='品牌'||$scope.currentcar.num=='型号'||$scope.currentcar.carnumber<=0){//||$scope.currentcar.filepath==''

                    alert('请检查是否选择正确');
                    return false;
                }
                $scope.inforData.carnum.push($scope.currentcar);
                $scope.addNum=$scope.inforData.carnum.length;
                CropperService.getCropperdata()[0]={
                    scale1:'',
                    scale2:'',
                    width:'',
                    height:'',
                    filename:'',
                    filepath:'上传照片，增加竞价积极性'
                };
            }else{
               $scope.inforData.draynum.push($scope.dray.value);
                $scope.addNum=$scope.inforData.draynum.length;
                if($scope.dray.value==12){
                    $scope.inforData.draytype[0]+=1;
                    $scope.dray.smallnum+=1;
                }else{
                    $scope.inforData.draytype[1]+=1;
                    $scope.dray.bignum+=1;
                }

            }

            //currentcar = null;
            $scope.currentcar = TransferService.resetCurrentCar();
            $scope.dray.value = 12;
            return true;
        };


        /*$scope.selectCarbrand = function(){
            $state.go('tab.getCarBrandList');
        }*/

        $('#uploadfile').bind('change',function(){//jquery监听隐藏文本框值变化

            var fd = new FormData();
            fd.append("name", "车辆图片");
            fd.append("files", document.getElementById("uploadfile").files[0]);

            $scope.currentcar.filename = '';
            $scope.$apply();

            var xhr = new XMLHttpRequest();
            xhr.open("POST" ,"/uploadFiles" , true);
            xhr.setRequestHeader('Authorization','Bearer ' +  localStorage.getItem('token'))//$window.sessionStorage.token
            xhr.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    document.getElementById('progress').innerHTML = '已上传 '+percentComplete.toString() + '%';
                }


            }, false);
            xhr.send(fd);
            xhr.onload = function(e) {
                if (this.status == 200) {
                    //$scope.inforData.fileName = this.responseText;
                    $scope.addNum=$scope.inforData.carnum.length;
                    document.getElementById('progress').innerHTML = '';
                    $scope.currentcar.filepath = this.responseText;
                    $scope.currentcar.filename = this.responseText.substring(0,10)+'.jpg';
                    $scope.$apply();
                }
            };

        });

    })
    .controller('CarBrandListCtrl',function($scope,$state,$stateParams,$location,TransferService){

        $scope.carbrands = TransferService.getCarbrandList().carbrand;
console.log($scope.carbrands)
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        $scope.myScroll1 = new IScroll('#wrapper1', { mouseWheel: true,click:true });//初始化ISCroll

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
            $scope.myScroll1.refresh();
        },500);
        $scope.goTo = function (id) {
            $location.hash(id);
            //$anchorScroll();
            $scope.myScroll.refresh();
        }
        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.selectCarbrand = function(id,brand){
            TransferService.getCurrentCar().brand = brand;
            TransferService.getCurrentCar().bid = id;
            /*TransferService.getInforData().carnum.push(id);*/
            /*TransferService.getInforData().carbrand = brand;
            TransferService.getInforData().carbrandid = id;*/
            //选定车牌后请求对应型号
            TransferService.getCurrentCar().num='型号';
            TransferService.getCarbrandList().carnums=[];
            TransferService.getCarNumList(id);

            $state.go('tab.transferAddCar');
        }

    })
    .controller('CarNumListCtrl',function($scope,$state,$stateParams,TransferService){

        $scope.carnums = TransferService.getCarbrandList().carnums;//TransferService.getCarNums();

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        setTimeout(function(){//因为有冲突等会执行scope.$apply();
            $scope.myScroll.refresh();
        },500);

        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.selectCarnum = function(id,num){
            TransferService.getCurrentCar().num = num;
            TransferService.getCurrentCar().nid = id;
            //TransferService.getInforData().carnum.push(id);
            /*TransferService.getInforData().carnumid = id;*/
            $state.go('tab.transferAddCar');
        }

    })
    .controller('CarListCtrl',function($scope,$state,$stateParams,TransferService){

        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);


        $scope.inforData = TransferService.getInforData();
        $scope.type = $scope.inforData.type;
        if($scope.type==1){
            $scope.carnum = $scope.inforData.carnum;//获取车辆数组
            TransferService.getCurrenttab().state = false;//设置零散车辆为默认显示的页面
        }else{
            TransferService.getCurrenttab().state = true;

            $scope.draylsit=[];
            $scope.draynum = $scope.inforData.draynum;
            for(var i=0;i<$scope.draynum.length;i++){
                if($scope.draynum[i]==12){
                    $scope.draylsit.push({type:'小板',num:12});
                }else{
                    $scope.draylsit.push({type:'大板',num:24});
                }
            }
        }
        $scope.goBack = function(){
            $state.go('tab.transferAddCar');
        };

        $scope.pop1 = false;
        var index;
        $scope.confirm = function(idx){
            $scope.pop1 = true;
            index = idx;
        }
        $scope.delSelect = function(){

           /* if(!confirm("确定要删除此项吗？")){
                return;
            }*/
            if($scope.type==1){
                $scope.carnum.splice(index,1);//删除选中的元素
            }else{
                //alert(index);
                if($scope.draylsit[index].num==12){
                    TransferService.getDray().smallnum-=1;
                    TransferService.getInforData().draytype[0]-=1;
                }else{
                    TransferService.getDray().bignum-=1;
                    TransferService.getInforData().draytype[1]-=1;
                }
                $scope.draynum.splice(index,1);
                $scope.draylsit.splice(index,1);


            }
            $scope.pop1 = false;
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },300);

    })
    .controller('CompleteCtrl',function($scope,$state,$stateParams,$interval){
        $scope.isOk = $stateParams.isOk;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.times=3;
        var timer = $interval(function(){
            $scope.times-=1;
            if($scope.times==0){
                $scope.times= 0;
                $interval.cancel(timer);
                $state.go('tab.myTransfer',{random:'update'});
            }
        },1000);


        $scope.goBack = function(){
            $state.go('tab.transfer');
        };

    })
    .controller('CompleteCtrlQuo',function($scope,$state,$stateParams,$interval){
        $scope.isOk = $stateParams.isOk;
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true,click:true });//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
        $scope.times=3;
        var timer = $interval(function(){
            $scope.times-=1;
            if($scope.times==0){
                $scope.times= 0;
                $interval.cancel(timer);
                $state.go('tab.myOrders');
            }
        },1000);
        $scope.goBack = function(){
            $state.go('tab.myTransfer',{random:'update'});
        };

    })
    .controller('CropperCtrl',function($scope,$state,$stateParams){
        $scope.scale1 = $stateParams.scale1;
        $scope.scale2 = $stateParams.scale2;
        $scope.width = $stateParams.width;
        $scope.height = $stateParams.height;
        $scope.urltype = $stateParams.urltype;
        $scope.goBack = function(){
            if($stateParams.urltype=='transfer'){//判断哪个页面进来的，回到哪个页面
                $state.go('tab.transferAddCar');
            }else if($stateParams.urltype == 'upheader'){
                $state.go('tab.center');
            }

        };



    });

